<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="用户id" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="支付金额" prop="amount">
              <el-input v-model="queryParams.amount" placeholder="请输入支付金额" clearable @keyup.enter="handleQuery"
                @input="(val) => (queryParams.amount = formatAmount(val))" />
            </el-form-item>

            <el-form-item label="支付方式" prop="payChannel">
              <el-input v-model="queryParams.payChannel" placeholder="请输入支付方式" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="支付状态" prop="payStatus">
              <el-input v-model="queryParams.payStatus" placeholder="请输入支付状态" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <!-- 新增充值相关控件 -->
              <!-- <el-input v-model="rechargeForm.payId" placeholder="支付ID" clearable
                style="width: 120px; margin-left: 10px" />
              <el-input v-model="rechargeForm.amount" placeholder="充值金额" clearable style="width: 120px"
                @input="handleAmountInput" />
              <el-button type="success" icon="Plus" :loading="buttonLoading" @click="handleRecharge">充值</el-button> -->
            </el-form-item>
            <!-- 在模板的充值表单部分添加按钮组 -->
            <el-form-item>
              <el-input v-model="rechargeForm.payId" placeholder="支付ID" clearable
                style="width: 120px; margin-left: 10px" />
              <!-- <el-input v-model="rechargeForm.amount" placeholder="充值金额" clearable style="width: 120px" @input="handleAmountInput" /> -->
              <el-input v-model="rechargeForm.amount" placeholder="充值金额" clearable style="width: 120px" readonly />
              <el-button type="success" icon="Plus" :loading="buttonLoading" @click="handleRecharge">充值</el-button>
              <div class="fixed-amounts mt-2">
                <el-button v-for="amount in fixedAmounts" :key="amount" @click="setAmount(amount)" class="m-1"
                  :type="rechargeForm.amount === amount ? 'primary' : ''">
                  {{ amount }}元
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['pay:pay:edit']">修改</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="TPayList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="支付id" align="center" prop="payId" v-if="true" />
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="用户id" align="center" prop="userId" />
        <el-table-column label="支付金额" align="center" prop="amount" />
        <el-table-column label="支付方式" align="center" prop="payChannel" />
        <el-table-column label="支付状态" align="center" prop="payStatus" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['pay:pay:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['pay:pay:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改TPay信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="TPayFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payChannel">
          <el-input v-model="form.payChannel" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="支付状态" prop="payStatus">
          <el-input v-model="form.payStatus" placeholder="请输入支付状态" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TPay" lang="ts">
import { listTPay, getTPay, updateTPay } from '@/api/pay/pay';
import { TPayVO, TPayQuery, TPayForm } from '@/api/pay/pay/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const TPayList = ref<TPayVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const TPayFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TPayForm = {
  payId: undefined,
  orderNo: undefined,
  userId: undefined,
  amount: undefined,
  payChannel: undefined,
  payStatus: undefined
};
const data = reactive<PageData<TPayForm, TPayQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    userId: undefined,
    amount: undefined,
    payChannel: undefined,
    payStatus: undefined,
    params: {}
  },
  rules: {
    payId: [{ required: true, message: 'ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询TPay信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTPay(queryParams.value);
  TPayList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  TPayFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TPayVO[]) => {
  ids.value = selection.map((item) => item.payId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  try {
    loading.value = true;
    await addTPay({}); // 直接调用接口，不需要表单数据
    proxy?.$modal.msgSuccess('数据同步启动成功');
    await getList(); // 刷新列表
  } catch {
    // 错误处理
  } finally {
    loading.value = false;
  }
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TPayVO) => {
  reset();
  const _id = row?.payId || ids.value[0];
  const res = await getTPay(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改TPay信息';
};

/** 提交按钮 */
const submitForm = () => {
  TPayFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.payId) {
        await updateTPay(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTPay(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TPayVO) => {
  const _ids = row?.payId || ids.value;
  await proxy?.$modal.confirm('是否确认删除TPay信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTPay(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

// 在响应式数据区域添加充值表单
const rechargeForm = reactive({
  payId: undefined as string | undefined, // 仅保留字符串类型
  amount: undefined as number | undefined
});
// 添加固定金额配置
const fixedAmounts = [1, 6, 18, 30, 68, 118, 198, 348, 648, 898, 1298];
const setAmount = (amount: number) => {
  rechargeForm.amount = amount;
};

// 添加充值处理方法
// 修改后的handleRecharge方法
const handleRecharge = async () => {
  if (!rechargeForm.payId || !rechargeForm.amount) {
    proxy?.$modal.msgError('请填写支付ID和充值金额');
    return;
  }
  if (rechargeForm.amount <= 0) {
    proxy?.$modal.msgError('充值金额必须大于0');
    return;
  }

  try {
    buttonLoading.value = true;
    // 获取完整支付记录
    const { data: currentData } = await getTPay(rechargeForm.payId);

    // 构造包含所有字段的更新数据
    const updateData: TPayForm = {
      ...currentData, // 保留原有字段
      payId: rechargeForm.payId,
      amount: Number(currentData.amount) + Number(rechargeForm.amount)
    };

    await updateTPay(updateData);
    proxy?.$modal.msgSuccess(`成功充值 ${rechargeForm.amount.toFixed(2)} 元`);

    // 清空表单并刷新
    rechargeForm.payId = undefined;
    rechargeForm.amount = undefined;
    await getList();
  } catch (error) {
    console.error('完整错误信息:', error);
    proxy?.$modal.msgError(`操作失败：${error.response?.data?.msg || '请检查支付ID是否正确'}`);
  } finally {
    buttonLoading.value = false;
  }
};
// 添加金额格式化方法
const formatAmount = (value) => {
  return value
    .replace(/[^\d.]/g, '')
    .replace(/(\..*)\./g, '$1')
    .replace(/(\.\d{2}).*/g, '$1');
};
// 优化后的金额输入处理
const handleAmountInput = (value) => {
  // 过滤非数字和小数点
  const filteredValue = value
    .replace(/[^\d.]/g, '')
    .replace(/(\..*)\./g, '$1') // 禁止多个小数点
    .replace(/(\.\d{2}).*/g, '$1'); // 限制两位小数
  // 转换为数字并保留两位小数
  rechargeForm.amount = filteredValue ? parseFloat(filteredValue) : undefined;
};
onMounted(() => {
  getList();
});
</script>
